const { Router } = require("express");
const Wechat = require("../model/Wechat");
const axios = require("axios");
const JWT = require("jsonwebtoken");
const router = new Router();
const tokenExpiration = 30 * 24 * 60 * 60;
//http://localhost:8000/api/wechat
router.post("/getcode", async (req, res) => {
  //获取小程序登录的code
  // 使用code换取openid
  //发送请求给微信的服务器
  const result = await axios.get(
    "https://api.weixin.qq.com/sns/jscode2session",
    {
      params: {
        appid: "wxfb4cfbb42c17c14f",
        secret: "2354bb208c717313656ad42a19158985",
        js_code: req.body.code,
        grant_type: "authorization_code",
      },
    }
  );

  const openid = result.data.openid;
  const session_key = result.data.session_key;
  // console.log(123);
  // 判断是不是新用户
  // 如果是新用户，需要静默注册
  let user = await Wechat.findOne({ openid }).lean();
  if (user) {
    //老用户,更新session_key,直接登录
    await Wechat.updateOne({ openid }, { session_key });
  } else {
    //新用户,先注册
    user = await new Wechat({ openid, session_key }).save();
    //再登录
  }

  //登录,生成token
  const token = JWT.sign(user, "hello world", {
    expiresIn: tokenExpiration,
  });

  //相应给小程序
  res.json({ code: 0, message: "ok", token: token });
});
router.get("/all", (req, res) => {
  const token = req.headers.authorization;
  console.log(token);
  try {
    // 验证并解码 token
    const decodedToken = JWT.verify(
      token.replace("Bearer ", ""),
      "hello world"
    );

    // 这里的 decodedToken 将包含之前签发 token 时的用户信息
    // 在这里可以继续处理其他逻辑

    res.json({ code: 0, message: "ok", data: decodedToken });
  } catch (err) {
    // 如果 token 验证失败，则返回错误响应
    res.status(401).json({ message: "Invalid token" });
  }
});
module.exports = router;
